import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    console.log(response) //response中是包含有响应头的，响应头 response.headers。 响应体是response.data
    if(response.request.responseURL.includes("/qs") || response.request.responseURL.includes("/slogt")
      || response.request.responseURL.includes("/slogq")){ //获取图片的请求，需要特殊处理
      if(response.status !== 200){
        Message({
          message: '获取图片发生了错误',
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject(new Error('获取图片发生了错误'));
      }
      return response;
    }

    const res = response.data;

    //console.log(res)
    // if the custom code is not 0, it is judged as an error.
    if (res.status !== 0) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      });

      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      console.log("发送请求成功...." + response.request.responseURL)
      return res;
    }
  },
  error => {
    console.log('发送请求失败....' + error) // for debug
    console.log(error)
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
